package com.gqz.config;

import com.gqz.domain.SysUser;
import com.gqz.utils.JsonResult;
import com.gqz.utils.UserTools;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import com.alibaba.fastjson.JSONObject;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;

@Component
public class LoginInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        SysUser userInfo = UserTools.getUserInfo(request);

        if (userInfo == null) {
            // 设置返回的编码格式
            response.setContentType("application/json;charset=utf-8");
            JsonResult result = JsonResult.custom(false, "请登录之后访问!", "401", null);
            // 2.2 将返回对象转成字符串
            String jsonString = JSONObject.toJSONString(result);

            // 2.3 将json类型的字符串返回给前端
            PrintWriter writer = response.getWriter();
            writer.println(jsonString);
            return false;
        }
        return true;
    }
}
